import React, { Component } from "react";
import { connect } from "dva";
import moment from "moment";
import {
  Card,
  Button,
  Form,
  Input,
  Row,
  Col,
  Select,
  Radio,
  InputNumber,
  DatePicker,
  TreeSelect
} from "antd";
import SelectModal from "./components/SelectModal";
import styles from "./PushPlanEdit.less";

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD HH:mm:ss";

const oneLine = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 }
  }
};

const halfLine = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};

@connect(({ pushPlan }) => ({ pushPlan }))
@Form.create()
class PushPlanEdit extends Component {
  state = {
    modalVisible: false,
    pushTypeDisable: true
  };

  componentDidMount() {
    // 加载下拉框
    const { planDetail: { appId } = {} } = this.props.pushPlan;
    this.props.dispatch({ type: "pushPlan/getStaticData" });
    if (appId) {
      this.props.dispatch({
        type: "pushPlan/getTrigger",
        payload: appId
      });
    }
  }

  componentWillUnmount() {
    this.props.dispatch({ type: "pushPlan/clearDetail" });
  }

  openModal = () => {
    this.setState({ modalVisible: true });
  };

  closeModal = () => {
    this.setState({ modalVisible: false });
  };

  // modal点击确认回调
  confirm = (userIdArr, userNameArr) => {
    const {
      form: { setFieldsValue }
    } = this.props;
    setFieldsValue({
      pushObject: userIdArr,
      pushObjectDesc: userNameArr
    });
    this.setState({ modalVisible: false });
  };

  // 返回列表
  cancel = () => {
    this.props.history.push("/pushPlan");
  };

  // 推送计划编辑保存
  save = () => {
    const { form } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        this.props.dispatch({ type: "pushPlan/addPlan", payload: values });
      }
    });
  };

  // 日期选择回调
  handleDatePickerChange = values => {
    this.props.dispatch({
      type: "pushPlan/changeTime",
      payload: {
        effTime: values[0] ? values[0].format(dateFormat) : null,
        expTime: values[1] ? values[1].format(dateFormat) : null
      }
    });
  };

  // 单位选择回调
  unitChange = value => {
    this.props.dispatch({ type: "pushPlan/changeTimesUnit", payload: value });
  };

  // 数字输入框回调
  timesChange = value => {
    this.props.dispatch({ type: "pushPlan/changePushTimes", payload: value });
  };

  onSceneIdChange = (value, { props: { scenetype } = {} }) => {
    const {
      form: { setFieldsValue }
    } = this.props;
    setFieldsValue({
      pushType: scenetype === "F" || scenetype === "G" ? "A2" : "A1"
    });
    if (scenetype === "G") {
      setFieldsValue({ pushObjectType: "T3" });
    }
    this.setState({ pushTypeDisable: scenetype !== "G" });
  };

  validateSceneId = (rule, value, callback) => {
    const {
      pushPlan: {
        staticData: { sceneList = [] } = {},
        planDetail: { sceneId } = {}
      } = {}
    } = this.props;
    const selected = sceneList.find(({ id }) => id === value) || {};
    if (
      selected.id !== +sceneId &&
      selected.sceneType === "G" &&
      selected.isPlan
    ) {
      callback("该自定义模型场景已匹配计划!");
    } else {
      callback();
    }
  };

  render() {
    const {
      form: {
        getFieldDecorator,
        getFieldsValue,
        getFieldValue,
        setFieldsValue
      },
      pushPlan
    } = this.props;
    const { modalVisible, pushTypeDisable } = this.state;
    const {
      pushObjectType,
      timeType,
      periodType,
      pushType,
      pushObjectDesc = [],
      pushObject = []
    } = getFieldsValue();
    const {
      staticData,
      planDetail = {},
      effTime,
      expTime,
      pushTimes,
      timesUnit
    } = pushPlan;
    const {
      sceneList = [],
      pushAppList = [],
      pushWayList = [],
      triggerList = [],
      objectTypeList = [],
      orgTree = []
    } = staticData;

    // 场景下拉框
    const sceneOption = sceneList.map(({ name, id, sceneType }) => (
      <Option value={id} key={id} scenetype={sceneType}>
        {name}
      </Option>
    ));

    // 推送应用下拉框
    const appOption = pushAppList.map(({ appName, id }) => (
      <Option key={id}>{appName}</Option>
    ));

    // 推送方式下拉框
    const wayOption = pushWayList.map(({ pushWay, id }) => (
      <Option key={id}>{pushWay}</Option>
    ));

    // 触发方式下拉框
    const triggerOption = triggerList.map(({ trigger, id }) => (
      <Option key={id}>{trigger}</Option>
    ));

    // 推送对象类型下拉框
    const objectTypeOption = objectTypeList.map(({ valueDesc, id }) => (
      <Option key={id}>{valueDesc}</Option>
    ));

    // 指定推送人推送对象下拉框
    const objectOption = pushObject.map((item, index) => (
      <Option key={item} value={item}>
        {pushObjectDesc[index]}
      </Option>
    ));

    const unit = [
      { key: "day", value: "天" },
      { key: "hour", value: "时" },
      { key: "minute", value: "分" },
      { key: "second", value: "秒" }
    ];
    const unitOption = unit.map(({ key, value }) => (
      <Option key={key}>{value}</Option>
    ));

    return (
      <Card
        className={styles.root}
        title="基础信息"
        headStyle={{ textAlign: "center" }}
      >
        <SelectModal
          select={getFieldValue("pushObject")}
          selectdesc={getFieldValue("pushObjectDesc")}
          visible={modalVisible}
          closeModal={this.closeModal}
          confirm={this.confirm}
        />
        <Form>
          <Row>
            <Col span={12}>
              <FormItem label="计划名称" {...halfLine}>
                {getFieldDecorator("planName", {
                  rules: [
                    {
                      required: true,
                      message: "请输入计划名称!"
                    },
                    {
                      pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
                      message: "计划名称含非法字符!"
                    },
                    {
                      max: 30,
                      message: "不得超过30个字符"
                    }
                  ],
                  initialValue: planDetail.planName
                })(<Input placeholder="请输入" />)}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label="场景名称" {...halfLine}>
                {getFieldDecorator("sceneId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择场景名称!"
                    },
                    {
                      validator: this.validateSceneId
                    }
                  ],
                  initialValue: planDetail.sceneId && Number(planDetail.sceneId)
                })(
                  <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                    placeholder="请选择"
                    onChange={this.onSceneIdChange}
                  >
                    {sceneOption}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label="接入应用" {...halfLine}>
                {getFieldDecorator("appId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择接入应用!"
                    }
                  ],
                  initialValue: planDetail.appId
                    ? String(planDetail.appId)
                    : undefined
                })(
                  <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                    placeholder="请选择"
                    onChange={value => {
                      this.props.form.setFieldsValue({ opTypeCode: undefined });
                      this.props.dispatch({
                        type: "pushPlan/getTrigger",
                        payload: value
                      });
                    }}
                  >
                    {appOption}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label="消息接收应用" {...halfLine}>
                {getFieldDecorator("objectAppId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择消息接收应用!"
                    }
                  ],
                  initialValue: planDetail.objectAppId
                    ? String(planDetail.objectAppId)
                    : undefined
                })(
                  <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                    placeholder="请选择"
                  >
                    {appOption}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label="推送方式" {...halfLine}>
                {getFieldDecorator("pushType", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送方式!"
                    }
                  ],
                  initialValue: planDetail.pushType || undefined
                })(
                  <Select
                    placeholder="请选择推送场景"
                    disabled={pushTypeDisable}
                  >
                    {wayOption}
                  </Select>
                )}
              </FormItem>
            </Col>
            {pushType === "A1" && (
              <Col span={12}>
                <FormItem label="触发动作" {...halfLine}>
                  {getFieldDecorator("opTypeCode", {
                    rules: [
                      {
                        required: true,
                        message: "请选择触发方式!"
                      }
                    ],
                    initialValue: planDetail.opTypeCode || undefined
                  })(<Select placeholder="请选择">{triggerOption}</Select>)}
                </FormItem>
              </Col>
            )}
            {pushType === "A2" && (
              <Col span={24}>
                <FormItem label="推送频率" {...oneLine}>
                  {getFieldDecorator("timeType", {
                    rules: [
                      {
                        required: true,
                        message: "请输入计划名称!"
                      }
                    ],
                    initialValue: planDetail.timeType || undefined
                  })(
                    <RadioGroup>
                      <Radio value="一月/次">一月/次</Radio>
                      <Radio value="一周/次">一周/次</Radio>
                      <Radio value="一天/次">一天/次</Radio>
                      <Radio value="一小时/次">一小时/次</Radio>
                      <Radio value="5分钟/次">5分钟/次</Radio>
                      <Radio value="自定义">
                        自定义
                        {timeType === "自定义" && (
                          <div style={{ display: "inline-block" }}>
                            <Select
                              style={{ marginLeft: 10, width: 70 }}
                              defaultValue={timesUnit}
                              onChange={value => this.unitChange(value)}
                            >
                              {unitOption}
                            </Select>
                            <InputNumber
                              placeholder="频率数值"
                              style={{ marginLeft: 10, width: 120 }}
                              defaultValue={pushTimes}
                              precision={0}
                              onChange={value => this.timesChange(value)}
                            />
                          </div>
                        )}
                      </Radio>
                    </RadioGroup>
                  )}
                </FormItem>
              </Col>
            )}
          </Row>
          <Row>
            <Col span={12}>
              <FormItem label="推送对象类型" {...halfLine}>
                {getFieldDecorator("pushObjectType", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送对象类型!"
                    }
                  ],
                  initialValue: planDetail.pushObjectType || undefined
                })(
                  <Select
                    placeholder="请选择"
                    onChange={() => {
                      setTimeout(() => {
                        this.props.form.setFieldsValue({
                          pushObject: undefined,
                          pushObjectDesc: undefined
                        });
                      }, 50);
                    }}
                  >
                    {objectTypeOption}
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            {pushObjectType === "T2" && (
              <Col span={24}>
                <FormItem label="推送对象" {...oneLine}>
                  {getFieldDecorator("pushObject", {
                    rules: [
                      {
                        required: true,
                        message: "请输入推送对象!"
                      }
                    ],
                    initialValue: planDetail.pushObject || []
                  })(
                    <TreeSelect
                      treeData={orgTree}
                      dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                      allowClear
                      treeCheckable
                      showCheckedStrategy="SHOW_PARENT"
                    />
                  )}
                </FormItem>
              </Col>
            )}
            {pushObjectType === "T3" && (
              <Col span={24}>
                <FormItem label="推送对象" {...oneLine}>
                  {getFieldDecorator("pushObject", {
                    rules: [
                      {
                        required: true,
                        message: "请输入推送对象!"
                      }
                    ],
                    initialValue: planDetail.pushObject || []
                  })(
                    <Select
                      mode="multiple"
                      open={false}
                      autoClearSearchValue
                      showSearch={false}
                      onDeselect={value => {
                        const index = (pushObject || []).findIndex(
                          item => item === value
                        );
                        const temp = JSON.parse(
                          JSON.stringify(pushObjectDesc || [])
                        );
                        if (index > -1) {
                          temp.splice(index, 1);
                          setFieldsValue({ pushObjectDesc: temp });
                        }
                      }}
                      style={{ width: "calc(100% - 74px)", marginRight: 10 }}
                    >
                      {objectOption}
                    </Select>
                  )}
                  <Button type="primary" onClick={this.openModal}>
                    选择
                  </Button>
                </FormItem>
                <FormItem label="推送对象名称" style={{ display: "none" }}>
                  {getFieldDecorator("pushObjectDesc", {
                    initialValue: planDetail.pushObjectDesc || []
                  })(<Select mode="multiple" />)}
                </FormItem>
              </Col>
            )}
            <Col span={24}>
              <FormItem label="计划说明" {...oneLine}>
                {getFieldDecorator("comments", {
                  rules: [
                    {
                      required: true,
                      message: "请输入计划说明!"
                    }
                  ],
                  initialValue: planDetail.comments || undefined
                })(<TextArea placeholder="请输入" rows={4} cols={120} />)}
              </FormItem>
            </Col>
            <Col span={24}>
              <FormItem label="计划有效期" {...oneLine}>
                {getFieldDecorator("periodType", {
                  rules: [
                    {
                      required: true,
                      message: "请输入计划有效期!"
                    }
                  ],
                  initialValue:
                    planDetail.periodType === "不限" ? "不限" : "自定义"
                })(
                  <RadioGroup>
                    <Radio value="不限">不限</Radio>
                    <Radio value="1年有效">1年有效</Radio>
                    <Radio value="1月有效">1月有效</Radio>
                    <Radio value="1周有效">1周有效</Radio>
                    <Radio value="当天有效">当天有效</Radio>
                    <Radio value="自定义">
                      自定义
                      {periodType === "自定义" ? (
                        <RangePicker
                          style={{ marginLeft: 15, width: 198 }}
                          format={dateFormat}
                          defaultValue={
                            effTime ? [moment(effTime), moment(expTime)] : []
                          }
                          onChange={values =>
                            this.handleDatePickerChange(values)
                          }
                          showTime={{
                            defaultValue: [
                              moment("00:00:00", "HH:mm:ss"),
                              moment("23:59:59", "HH:mm:ss")
                            ]
                          }}
                        />
                      ) : null}
                    </Radio>
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div className={styles.buttonGroup}>
          <Button className={styles.button} onClick={this.cancel}>
            取消
          </Button>
          <Button className={styles.button} type="primary" onClick={this.save}>
            保存
          </Button>
        </div>
      </Card>
    );
  }
}

export default PushPlanEdit;
